package cn.swunet.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;


/**
 * 
 * @author: arosen.swunet@qq.com
 *
 * @date: 2020年4月23日
 *
 * @TDDO: 基本database操作
 */
public abstract class BaseDao<T> {
	protected Class<T> clazz;
	public BaseDao() {
		// 反射  reflection
		Type superClass = getClass().getGenericSuperclass();
		if (superClass instanceof ParameterizedType) {
			ParameterizedType parameteriedType = (ParameterizedType)superClass;
			Type[] typeArgs = parameteriedType.getActualTypeArguments();
			if (typeArgs != null && typeArgs.length > 0) {
				if (typeArgs[0] instanceof Class) {
					clazz = (Class<T>) typeArgs[0];
				}
			}
		}
	}

	/**
	 * 
	 * @author:arosen.swunet@qq.com
	 * @return:List<T>
	 * 			查询结果
	 * @TODO:
	 */
	protected synchronized List<T> getList(String sql, Object ...args) {
		QueryRunner runner = new QueryRunner(DBTools.getDataSource());
		BeanListHandler<T> beanListHandler = new BeanListHandler<T>(clazz);
		try {
			return runner.query(sql, beanListHandler, args);
		} catch (SQLException e) {
			e.printStackTrace();
			return new ArrayList<T>();
		}
	}
	
	/**
	 * 
	 * @author:arosen.swunet@qq.com
	 * @return:T
	 * 		查询结果
	 * @TODO:
	 */
	protected synchronized T getOne(String sql, Object ...args) {
		QueryRunner runner = new QueryRunner(DBTools.getDataSource());
		BeanHandler<T> beanHandler = new BeanHandler<T>(clazz);
		try {
			return runner.query(sql, beanHandler, args);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
	 * @author:arosen.swunet@qq.com
	 * @return:int
	 * 		受影响的行数
	 * @TODO:
	 */
	protected synchronized int update(String sql, Object ...args) {
		QueryRunner runner = new QueryRunner(DBTools.getDataSource());
		try {
			return runner.update(sql, args);
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
	}
}
